package com.cwz.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cwz.entity.Material;
import com.cwz.entity.MaterialInventoryRecord;
import com.cwz.entity.User;
import com.cwz.excel.MaterialExcel;
import com.cwz.excel.MaterialExcelListener;
import com.cwz.exception.ErrorEnum;
import com.cwz.exception.ServiceException;
import com.cwz.mapper.MaterialInventoryRecordMapper;
import com.cwz.mapper.MaterialMapper;
import com.cwz.param.MaterialHttpQueryParam;
import com.cwz.param.MaterialInventoryRecordHttpQueryParam;
import com.cwz.param.MaterialInventoryStatisticsParam;
import com.cwz.service.MaterialService;
import com.cwz.vo.MaterialInventoryStatisticsVO;
import com.mysql.cj.util.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author wenZhen
 * @create 2024-08-17 8:48
 */
@Service
public class MaterialServiceImpl implements MaterialService {


    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    @Resource
    private MaterialMapper materialMapper;

    @Resource
    private MaterialInventoryRecordMapper materialInventoryRecordMapper;

    @Resource
    private MaterialExcelListener materialExcelListener;


    @Override
    public Map<String, Object> save(Material material, HttpSession session) {

        QueryWrapper<Material> wrapper = new QueryWrapper<Material>();
        wrapper.eq("MATERIAL_NAME", material.getMaterialName());

        if (materialMapper.exists(wrapper)) {
            throw new ServiceException(ErrorEnum.MATERIAL_EXISTS);
        }

        materialMapper.insert(material);

        return success();
    }

    @Override
    public Map<String, Object> batchSave(MultipartFile file, HttpSession session) {
        checkAdminRole(session);
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!(".xls".equals(ext) || ".xlsx".equals(ext))) {
            throw new ServiceException(ErrorEnum.FILE_FORMAT_NOT_SUPPORTED);
        }

        long size = file.getSize();
        if (size > 1024 * 1024 * 10) {
            throw new ServiceException(ErrorEnum.FILE_SIZE_TOO_LARGE);
        }

        try {
            EasyExcel.read(file.getInputStream(), MaterialExcel.class, materialExcelListener)
                    .sheet().doRead();
            return success();
        } catch (IOException e) {
            throw new ServiceException(ErrorEnum.EXCEL_PARSE_ERROR);
        }
    }

    @Override
    public Map<String, Object> page(MaterialHttpQueryParam param, HttpSession session) {
        checkAdminRole(session);
        QueryWrapper queryWrapper = new QueryWrapper();
        IPage<Material> page = new Page<>(param.getCurrent(), param.getSize());

        queryWrapper.like(!StringUtils.isNullOrEmpty(param.getMaterialName()), "MATERIAL_NAME", param.getMaterialName())
                .between((param.getLowStock() != null) && (param.getHighStock() != null), "STOCK_AMOUNT", param.getLowStock(), param.getHighStock())
                .le((param.getLowStock() == null) && (param.getHighStock() != null), "STOCK", param.getHighStock())
                .ge((param.getLowStock() != null) && (param.getHighStock() == null), "STOCK", param.getLowStock());

        page = materialMapper.selectPage(page, queryWrapper);

        return success(page);
    }

    @Override
    public Map<String, Object> update(Material material, HttpSession session) {
        checkAdminRole(session);
        if (materialMapper.selectById(material.getId()) == null) {
            throw new ServiceException(ErrorEnum.MATERIAL_NOT_FOUND);
        }
        materialMapper.updateById(material);
        return success();
    }

    @Override
    public Map<String, Object> disable(Material material, HttpSession session) {
        checkAdminRole(session);
        return update(material, session);
    }

    @Override
    public Map<String, Object> detail(Integer id, HttpSession session) {
        checkAdminRole(session);
        Material material = materialMapper.selectById(id);
        if (material == null) {
            throw new ServiceException(ErrorEnum.MATERIAL_NOT_FOUND);
        } else {
            return success(material);
        }
    }

    @Transactional
    public Map<String, Object> inventory(MaterialInventoryRecord record, HttpSession session) {
        checkAdminRole(session);
        User user = (User) session.getAttribute("user");
        record.setOperator(user.getUsername());
        Material material = materialMapper.selectById(record.getMaterialId());
        if (material == null) {
            throw new ServiceException(ErrorEnum.MATERIAL_NOT_FOUND);
        }

        if (material.getDeleteStatus() == 1) {
            throw new ServiceException(ErrorEnum.MATERIAL_DISABLED);
        }

        if (record.getType() == 0 && material.getStockAmount() < record.getQuantity()) {
            throw new ServiceException(ErrorEnum.INSUFFICIENT_INVENTORY);
        }

        Material newMaterial = new Material();
        newMaterial.setId(record.getMaterialId());
        if (record.getType() == 0) {
            newMaterial.setStockAmount(material.getStockAmount() - record.getQuantity());
        } else {
            newMaterial.setStockAmount(material.getStockAmount() + record.getQuantity());
        }
        materialMapper.updateById(newMaterial);
        materialInventoryRecordMapper.insert(record);
        return success();
    }

    @Override
    public Map<String, Object> inventoryPage(MaterialInventoryRecordHttpQueryParam param, HttpSession session) {
        checkAdminRole(session);
        IPage<MaterialInventoryRecord> page = new Page<>(param.getCurrent(), param.getSize());
        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq(param.getMaterialId() != null, "MATERIAL_ID", param.getMaterialId())
                .eq((!StringUtils.isNullOrEmpty(param.getOperator())), "OPERATOR", param.getOperator())
                .eq(param.getType() != null, "TYPE", param.getType())
                .le((StringUtils.isNullOrEmpty(param.getStartDate())) && !(StringUtils.isNullOrEmpty(param.getEndDate())), "OPERATE_DATE", param.getEndDate())
                .ge((!StringUtils.isNullOrEmpty(param.getStartDate())) && (StringUtils.isNullOrEmpty(param.getEndDate())), "OPERATE_DATE", param.getStartDate())
                .between(!(StringUtils.isNullOrEmpty(param.getStartDate())) && !(StringUtils.isNullOrEmpty(param.getEndDate())), "OPERATE_DATE", param.getStartDate(), param.getEndDate());

        page = materialInventoryRecordMapper.selectPage(page, queryWrapper);
        return success(page);

    }

    @Override
    public Map<String, Object> statistic(MaterialInventoryStatisticsParam param, HttpSession session) {

        checkAdminRole(session);
        /*
         * 如果前端没有指定统计哪一年  哪一月  后端可以有2种策略
         * 1.指定默认的年和月
         * 2，检查参数 判空  抛异常
         * */
        if (param.getYear() == null) {
            throw new ServiceException(ErrorEnum.REQUEST_PARAMETERS_NOT_SPECIFIED);
        }
        if (param.getMonth() == null) {
            throw new ServiceException(ErrorEnum.REQUEST_PARAMETERS_NOT_SPECIFIED);
        }
        String key=param.getYear()+"-"+param.getMonth();
        List<MaterialInventoryStatisticsVO> list = (List<MaterialInventoryStatisticsVO>) redisTemplate.opsForValue().get(key);
        if (list==null||list.size()==0){
            list=materialMapper.statistic(param);
            redisTemplate.opsForValue().set(key,list,10, TimeUnit.SECONDS);
        }

        return success(list);

    }

}
